package com.example.clientapplication

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.example.joke.UserAidl

class MainActivity : AppCompatActivity() {

    private var mUserAidl : UserAidl? = null

    private val mServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            // 连接好了
            mUserAidl = UserAidl.Stub.asInterface(service)

        }

        override fun onServiceDisconnected(p0: ComponentName?) {
            // 断开连接
            mUserAidl = null
        }

    }

    private lateinit var tvName: TextView
    private lateinit var tvPwd: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tvName = findViewById(R.id.tv_name)
        tvPwd = findViewById(R.id.tv_pwd)

        // 隐式意图
        val intent = Intent()
        intent.action = "com.example.joke.aidl.user"
        intent.setPackage("com.example.joke")
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)

        tvName.setOnClickListener {
            val userName = mUserAidl?.userName
            Toast.makeText(this, userName, Toast.LENGTH_LONG).show()
        }
        tvPwd.setOnClickListener {
            val pwd = mUserAidl?.userPwd
            Toast.makeText(this, pwd, Toast.LENGTH_LONG).show()
        }
    }

//    fun getUserName(view : View) {
//        val userName = mUserAidl?.userName
//        Toast.makeText(this, userName, Toast.LENGTH_LONG).show()
//    }
//
//    fun getPwd(view : View) {
//        val pwd = mUserAidl?.userPwd
//        Toast.makeText(this, pwd, Toast.LENGTH_LONG).show()
//    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(mServiceConnection)
    }
}